package com.sx.micowell.module.smartDevice;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.mvvm.bar.TitleBar;
import com.example.mvvm.base.ContainerActivity;
import com.example.mvvm.base.action.TitleBarAction;
import com.example.mvvm.base.data.DataBindingConfig;
import com.example.mvvm.until.LogUtils;
import com.example.mvvm.until.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.sx.micowell.BR;
import com.sx.micowell.R;
import com.sx.micowell.databinding.FragDeviceListBinding;
import com.sx.micowell.framework.app.IntentKey;
import com.sx.micowell.framework.app.MyFragment;
import com.sx.micowell.framework.arouth.RouteManager;
import com.sx.micowell.framework.arouth.RoutePath;
import com.sx.micowell.framework.model.smartDevice.SmartDeviceListModel;
import com.sx.micowell.framework.tools.AppDialogUtils;
import com.sx.micowell.module.smartDevice.adapter.DeviceBoundListAdapter;
import com.tuya.smart.android.ble.builder.BleConnectBuilder;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.sdk.api.IDevListener;
import com.tuya.smart.sdk.api.IResultCallback;
import com.tuya.smart.sdk.bean.DeviceBean;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: YY
 * @Time: 2021/10/8
 * @Describe 设备绑定列表
 */
@Route(path = RoutePath.SMART_DEVICE_BIND_LIST)
public class DeviceBindListFragment extends MyFragment<FragDeviceListBinding, ContainerActivity>
        implements TitleBarAction {

    private SmartDeviceListModel viewModel;

    private DeviceBoundListAdapter deviceListAdapter;

    IDevListener iDevListener = new IDevListener() {
        @Override
        public void onDpUpdate(String devId, String dpStr) {

        }

        @Override
        public void onRemoved(String devId) {

        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onStatusChanged(String devId, boolean online) {
            LogUtils.d("onStatusChanged "+devId+ " ---- "+online);
            if (deviceListAdapter != null) {
                if (deviceListAdapter.getData().size() > 0) {
                    for (DeviceBean item : deviceListAdapter.getData()) {
                        item.setIsOnline(online);
                        deviceListAdapter.notifyItemChanged(0);
                    }
                    hideDialog();
                }
            }
        }

        @Override
        public void onNetworkStatusChanged(String devId, boolean status) {

        }

        @Override
        public void onDevInfoUpdate(String devId) {

        }
    };


    @Override
    protected void initViewModel() {
        super.initViewModel();
        viewModel = getFragmentScopeViewModel(SmartDeviceListModel.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.frag_device_list, BR.viewModel, viewModel);
    }

    @Override
    protected void initView() {
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true).fitsSystemWindows(true).init();
        // toolbar点击事件
        getBinding().title.setOnTitleBarListener(this);

        getBinding().layoutEmpty.tvAddDevice.setOnClickListener(v ->
            startAddDevice()
        );
    }

    @Override
    protected void initData() {
        viewModel.queryHomeList();
    }

    @Override
    protected void initViewObservable() {
        super.initViewObservable();
        setDeviceBindList();
    }

    @Nullable
    @Override
    public TitleBar getTitleBar() {
        return getBinding().title;
    }

    @Override
    public void onLeftClick(View v) {
        getMyActivity().finish();
    }

    @Override
    public void onRightClick(View v) {
        startAddDevice();
    }

    public void setDeviceBindList() {
        getBinding().recyclerDevice.setNestedScrollingEnabled(false);
        getBinding().recyclerDevice.setLayoutManager(new LinearLayoutManager(getContext()));

        viewModel.deviceListData.observe(this, deviceBeans -> {
            if (deviceBeans != null && deviceBeans.size() > 0) {
                getBinding().layoutEmpty.line1.setVisibility(View.GONE);
                if (deviceListAdapter == null) {
                    deviceListAdapter = new DeviceBoundListAdapter(deviceBeans);
                    getBinding().recyclerDevice.setAdapter(deviceListAdapter);
                } else {
                    deviceListAdapter.getData().clear();
                    deviceListAdapter.addData(deviceBeans);
                    getBinding().recyclerDevice.setAdapter(deviceListAdapter);
                }

                // 列表点击
                deviceListAdapter.setOnItemClickListener((adapter, view, position) -> {
                    boolean isOnline = deviceBeans.get(position).getIsOnline();
                    String name = deviceBeans.get(position).getName();
                    String devId = deviceBeans.get(position).getDevId();

                    if (isOnline) {
                        // 在线
                        Bundle bundle = new Bundle();
                        bundle.putString(IntentKey.DATA, name);
                        bundle.putString(IntentKey.ID, devId);
                        startContainerActivity(
                                RouteManager.Companion.getInstance().getDeviceDataFragment(name, devId)
                                        .getClass().getCanonicalName(),
                                bundle);
                    } else {
                        // 离线
                        List<BleConnectBuilder> builderList = new ArrayList<>();
                        for (DeviceBean deviceBean : deviceBeans) {
                            TuyaHomeSdk.newDeviceInstance(deviceBean.devId).registerDevListener(iDevListener);
                            if (deviceBean.isBluetooth()) {
                                BleConnectBuilder builder = new BleConnectBuilder();
                                builder.setDevId(deviceBean.devId);
                                builderList.add(builder);
                            }
                        }
                        if (builderList.size() > 0) {
                            TuyaHomeSdk.getBleManager().connectBleDevice(builderList);
                            showDialog("正在配置");
                        }
                    }
                });

                // 长按移除
                deviceListAdapter.setOnItemLongClickListener((adapter, view, position) -> {
                    String deviceId = deviceBeans.get(position).getDevId();
                    AppDialogUtils.showBasicDialog(getContext(),
                            "提示", "确定要移除设备吗？", () -> {
                                TuyaHomeSdk.newDeviceInstance(deviceId).removeDevice(new IResultCallback() {
                                    @SuppressLint("NotifyDataSetChanged")
                                    @Override
                                    public void onSuccess() {
                                        ToastUtils.showShort("移除成功");
                                        viewModel.queryHomeList();
                                    }

                                    @Override
                                    public void onError(String code, String error) {
                                        LogUtils.d(error);
                                    }

                                });
                            });
                    return false;
                });

            } else {
                getBinding().recyclerDevice.setAdapter(null);
                getBinding().layoutEmpty.line1.setVisibility(View.VISIBLE);
            }
        });
    }

    public void startAddDevice() {
        startContainerActivity(
                RouteManager.Companion.getInstance().getSelectAddDeviceFragment()
                        .getClass().getCanonicalName(), null
        );
    }


}
